<template>
  <section>
    <el-dialog
      v-dialogDrag
      title="提示"
      :visible.sync="isViewWebsite"
      width="70%"
      :append-to-body="true"
      :close-on-click-modal="false"
      center
      @close="close"
      @opened="open"
    >
      <dialogHeader
        slot="title"
        title="网点选择"
        :style-type="$store.state.app.dialogType"
      />
      <div class="formBoxContain">
        <!--
            buttons: 按钮
            froms: 表单
            fromsField: 表单对应的字段
            tableOption: 网格项
            dynamicApiConfigs: 取值
         -->
        <!-- <one-table-template
        ref="isPopWindowsTable"
        :dynamic-buttons="buttons"
        :dynamic-components="froms"
        :dynamic-form-fields="fromsField"
        :dynamic-table-cols="tableOption"
        :dynamic-api-config="dynamicApiConfigs"
        :dynamic-is-show-select="true"
        :dynamic-is-init-table="true"
        :dynamic-is-fix-choose="false"
        :dynamic-is-fix-index="false"
        :dynamic-api-style="'restfuls'"
      /> -->
        <one-table-template
          ref="multipleTable"
          :dynamic-buttons="tableButtons"
          :dynamic-components="tableComponents"
          :dynamic-api-config="dynamicApiConfigs"
          :dynamic-table-defult-height="450"
          :dynamic-table-cols="tableCols"
          :dynamic-form-fields="formField"
          :dynamic-is-show-select="true"
          :dynamic-is-init-table="true"
          :dynamic-is-fix-choose="false"
          :dynamic-is-fix-index="false"
          :dynamic-is-show-more-btn="true"
          :callback-obj="callbackObj"
        />
      </div>
    </el-dialog>
  </section>
</template>

<script>
import dialogHeader from '@/components/dialogHeader'
import OneTableTemplate from '@/components/templates/oneTable'
import api from './api'
import { vehiclePdiPriceInquirys } from '@/api/se/vehiclePdiPriceInquiry'

export default {
  components: {
    dialogHeader,
    OneTableTemplate
  },
  // mixins: [oneTableWithViewTemplateMixins],
  props: {
    // 是否关闭弹窗
    isViewWebsite: {
      type: Boolean,
      default: false
    }
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      dynamicApiConfigs: vehiclePdiPriceInquirys.queryOrgDlrList,
      tableComponents:
           [
             {
               compKey: 'compKey1',
               labelName: '大区：',
               codeField: 'bigAreaId',
               component: () => import('@/components/org/commonSelect'),
               oFields: 'bigAreaId,bigAreaName',
               customObj: {
                 api: api.bigAreaQuery
               },
               type: 'dropdownList',
               isMul: false,
               isMust: true,
               span: 8
             },
             {
               compKey: 'compKey2',
               labelName: '小区：',
               codeField: 'smallAreaId',
               component: () => import('@/components/org/commonSelect'),
               oFields: 'smallAreaId,smallAreaName',
               disabled: true,
               options: [],
               type: 'dropdownList',
               isMul: false,
               isMust: true,
               span: 8
             },
             {
               compKey: 'compKey3',
               labelName: '省份：',
               codeField: 'provinceId',
               component: () => import('@/components/org/commonSelect'),
               oFields: 'provinceId,provinceName',
               customObj: {
                 api: api.provinceQuery
               },
               type: 'dropdownList',
               isMul: false,
               isMust: true,
               span: 8
             },
             {
               compKey: 'compKey4',
               labelName: '网点编码:',
               codeField: 'dlrCode',
               component: () => import('@/components/org/commonInput'),
               type: 'inputText',
               isMust: true,
               span: 8
             },
             {
               compKey: 'compKey5',
               labelName: '网点名称:',
               codeField: 'dlrShortName',
               component: () => import('@/components/org/commonInput'),
               type: 'inputText',
               isMust: true,
               span: 8
             },
             {
               compKey: 'compKey6',
               labelName: '城市：',
               codeField: 'cityId',
               component: () => import('@/components/org/commonSelect'),
               options: [],
               oFields: 'cityId,cityName',
               type: 'dropdownList',
               disabled: true,
               isMul: false,
               isMust: true,
               span: 8
             }
           ],
      formField: {},
      // 回调方法对象
      callbackObj: {
        // 网格点击回调事件
        onRowClick: (currentRow) => {
          this.onRightRowClick(currentRow)
        },
        // 手动勾选网格时，拿到勾选网格的数据
        onCheckSelect: (selection, row) => {
          this.selectiondata = selection
        },
        onCheckSelectChange: (selection) => {
          // this.onCheckSelectChange1(selection)
        }
      },
      tableButtons: [
        {
          compKey: 'button1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.$refs.multipleTable.queryTable(1),
          text: '查询',
          position: 'right'
        },
        {
          conmpKey: 'button1',
          type: '',
          size: 'small',
          clickEvent: () => this.notarize(),
          text: '选择',
          name: '',
          position: 'right' // 提交
        },
        {
          compKey: 'button2',
          type: '',
          size: 'small',
          icon: '',
          name: 'reset',
          clickEvent: () => {
            for (const attr in this.formField) {
              this.formField[attr] = ''
            }
          },
          text: '重置',
          position: 'right'
        }
      ],
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'dlrCode',
              label: '网点编码',
              align: 'center'
            },
            {
              prop: 'dlrShortName',
              label: '网点简称',
              align: 'center'
            },
            {
              prop: 'linkAddr',
              label: '网点地址',
              align: 'center'
            },
            {
              prop: 'bigAreaName',
              label: '大区',
              align: 'center'
            },
            {
              prop: 'smallAreaName',
              label: '小区',
              align: 'center'
            },
            {
              prop: 'provinceName',
              label: '省份',
              align: 'center'
            },
            {
              prop: 'orgTypeCn',
              label: '网点类型',
              align: 'center'
            },
            {
              prop: 'dlrStatusCn',
              label: '营业状态',
              align: 'center'
            }
          ]
    }
  },
  watch: {
    'formField.bigAreaId': function(val) {
      if (val) {
        this.linkageQuery({
          linkageField: 'bigAreaId,smallAreaId',
          apiUrl: api.smallAreaQueryByBig.APIUrl,
          linkageVal: val
        })
      } else {
        this.tableComponents.filter(o => o.codeField === 'smallAreaId')[0].disabled = true
      }
    },
    'formField.provinceId': function(val) {
      if (val) {
        this.linkageQuery({
          linkageField: 'provinceId,cityId',
          apiUrl: api.cityQuery.APIUrl,
          linkageVal: val
        })
      } else {
        this.tableComponents.filter(o => o.codeField === 'cityId')[0].disabled = true
      }
    }
  },
  mounted() {
  },
  created() {
    this.genFormField()
  },
  methods: {
    // linkageQuery
    linkageQuery(opt) {
      const params = {}
      const { apiUrl, linkageVal } = opt
      const [parentField, field] = opt['linkageField'].split(',')
      params[parentField] = linkageVal
      this.$requestAPI({
        apiUrl,
        variables: params
      }).then(res => {
        if (res.result === '1') {
          const comp = this.tableComponents.filter(o => o.codeField === field)[0]
          comp['options'] = res['rows']
          comp['disabled'] = false
        } else {
          this.$message(res.msg ? res.msg : '')
        }
      }).catch(err => {
        if (err.response.data.msg) {
          this.$message(err.response.data.msg)
        } else {
          this.$message(err.message)
        }
      })
    },
    genFormField() {
      const viewPageCode = this.$route.path
      this.genCodeFiled = this.genUtil(this.tableComponents)
      const formField = this.genCodeFiled()
      this.formField = this.$utils.getFormField(this, formField, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    },
    // 生成formField
    genUtil: (array) => (attr1 = 'codeField', attr2 = 'textField') => array.reduce((p, c) => {
      if (c[attr1].includes(',')) {
        const d = c[attr1].split(',')
        for (let i = 0; i < d.length; i++) {
          p[d[i]] = ''
        }
      } else {
        p[c[attr1]] = ''
      }
      // eslint-disable-next-line no-prototype-builtins
      c.hasOwnProperty(attr2) ? p[c[attr2]] = '' : ''
      return p
    }, {}),
    /**
     * @description 关闭弹窗
     * @time 2021、01、22
     */
    close() {
      this.$emit('close')
    },
    open() {
      this.$refs.isPopWindowsTable.queryTable(1)
    },
    // 确认
    notarize() {
      if (!this.selectiondata || this.selectiondata.length == 0) {
        this.$message({
          message: '请至少选择一条数据',
          type: 'warn',
          duration: 1000
        })
      } else {
        this.$emit('selectiondataPart', this.selectiondata)
        this.isViewWebsite = false
      }
    }
  }
}
</script>
<style scoped>
.formBoxContain {
  height: 600px;
}
</style>
